package com.czl.module_service.viewmodel

import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.ApproveBean
import com.czl.base.data.bean.tengyun.ListBean
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

class AssetHandleApprovalListViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var currentPage = 1
    var pageSize = 10
    val uc = UiChangeEvent()
    var titleNameObs = ObservableField("")

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<ListBean<ApproveBean>> = SingleLiveEvent()
        val loadFinallyEvent: SingleLiveEvent<Unit?> = SingleLiveEvent()
    }
    val reSearch: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 1
        this.getTaskListBySearch()
    })

    val onLoadMoreListener: BindingCommand<Void> = BindingCommand(BindingAction {
        this.getTaskListBySearch()
    })
    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        currentPage = 1
        this.getTaskListBySearch()
    })

    private fun getTaskListBySearch(
        titleName: String? = null
    ) {
        val taskType: Int? = 1
        val businessId: Int? = 11
        val statuses: Any? = intArrayOf(1,2,3,4)
        model.mTengYunHttpDataSource.getTaskListBySearch(
            GsonUtils.toJson(
                mapOf(
                    "pageNo" to currentPage,
                    "pageSize" to pageSize,
                    "userId" to model.getLocalUserInfo()?.userId,
                    "title" to titleNameObs.get(),
                    "taskType" to taskType,
                    "statuses" to statuses,
                    "businessId" to businessId
                )
            )
        ).compose(RxThreadHelper.rxSchedulerHelper(this))
            .doFinally {
                uc.loadFinallyEvent.postValue(null)
            }
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<ApproveBean>>>() {
                override fun onResult(t: BaseBean<ListBean<ApproveBean>>) {
                    if (t.state == 0) {
                        currentPage++
                        uc.loadCompleteEvent.postValue(t.data)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }
}